from django.shortcuts import render, redirect, reverse, Http404
from django.views import View
from django.contrib.auth.decorators import login_required

from . import models
from . import forms


class IndexView(View):
    template_name = 'app01/index.html'

    def get(self, request):
        return render(request, self.template_name)

#def index(request):
#    return render(request, 'app01/index.html')


@login_required
def topics(request):
    topics = models.Topic.objects.filter(owner=request.user).order_by('date_added')
    return render(request, 'app01/topics.html', {"topics": topics})


@login_required
def topic(request, topic_id):
    topic_id = int(topic_id)
    print(topic_id)
    topic = models.Topic.objects.get(id=topic_id)
    if topic.owner != request.user:
        raise Http404
    entries = topic.entry_set.order_by('-date_added')
    return render(request, 'app01/topic.html', {"topic": topic, "entries": entries})


@login_required
def new_topic(request):

    if request.method == "POST":
        form = forms.TopicForm(request.POST)
        if form.is_valid():
            new_topic = form.save(commit=False)
            new_topic.owner = request.user
            new_topic.save()
            return redirect(reverse('app01:topics'))

    else:
        form = forms.TopicForm()
        return render(request, 'app01/new_topic.html', {'form': form})


@login_required
def new_entry(request, topic_id):
    topic = models.Topic.objects.get(id=topic_id)

    if request.method == "POST":
        form = forms.EntryForm(request.POST)
        if form.is_valid():
            new_entry = form.save(commit=False)
            new_entry.topic = topic
            new_entry.save()
            return redirect(reverse('app01:topic', args=[topic_id]))
    else:
        form = forms.EntryForm()
        return render(request, 'app01/new_entry.html', {'topic': topic, 'form': form})


@login_required
def edit_entry(request, entry_id):
    entry = models.Entry.objects.get(id=entry_id)
    topic = entry.topic
    print(topic)
    if topic.owner != request.user:
        raise Http404

    if request.method == "POST":
        # ※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※
        form = forms.EntryForm(instance=entry, data=request.POST)
        if form.is_valid():
            form.save()
            return redirect(reverse("app01:topic", args=[topic.id]))

    else:
        # ※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※
        form = forms.EntryForm(instance=entry)
        return render(request, 'app01/edit_entry.html', {'topic': topic, 'form': form})
